﻿using Business.Service;
using Model;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;

namespace MvcAppWeb.Controllers
{
    public class LocationInfoController : BaseDataController
    {
        //
        // GET: /LocationInfo/

        public ActionResult LocationInfo()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="locationCode"></param>
        /// <param name="warehHuseId"></param>
        /// <param name="locationType"></param>
        /// <param name="sArea"></param>
        /// <param name="roadWay"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public JsonResult InitJsonResult(string locationCode, string warehHuseId, string locationType, string sArea, string roadWay, string status)
        {
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            int n = 0;
            string where = " where 1=1";
            if (!string.IsNullOrEmpty(warehHuseId))
            {
                if (int.TryParse(warehHuseId, out n))
                {
                    if (Convert.ToInt32(warehHuseId) != 0)
                    {
                        where += " and l.warehouseid='" + warehHuseId + "'";
                    }
                }
                else
                {
                    where += " and 1=2";
                }
            }
            if (!string.IsNullOrEmpty(locationCode))
            {
                where += " and l.LOCATIONCODE like'%" + locationCode + "%'";
            }
            if (!string.IsNullOrEmpty(locationType))
            {
                where += " and l.LOCATIONTYPE like'%" + locationType + "%'";
            }
            if (!string.IsNullOrEmpty(sArea))
            {
                where += " and l.Area like'%" + sArea + "%'";
            }
            if (!string.IsNullOrEmpty(roadWay))
            {
                where += " and l.RoadWay like'%" + roadWay + "%'";
            }
            if (!string.IsNullOrEmpty(status))
            {
                where += " and l.STATUS ='" + status + "'";
            }

            var retData = new object();
            BLocationInfo li = new BLocationInfo();
            retData = li.GetLocationInfoList(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <returns></returns>
        public JsonResult GetWarehouseList()
        {
            string defaultValue = Request["defaultValue"].ToString();
            var retData = new object();
            BLocationInfo nbl = new BLocationInfo();
            retData = nbl.GetWarehouseList(defaultValue).ToList();
            return Json(retData);
        }

        /// <summary>
        /// 获取货位信息              
        /// </summary>
        /// <param name="IsSetAll"></param>
        /// <returns></returns>
        public JsonResult LocationCodeList(string defaultValue)
        {
            var retData = new object();
            BLocationInfo nbl = new BLocationInfo();
            retData = nbl.GetLocationCodeList(defaultValue, "").ToList();
            return Json(retData);
        }

        /// <summary>
        /// 新增/修改货位信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string SaveData()
        {
            string sjson = string.Empty;
            try
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                Location location = new Location();
                location.LOCATIONCODE = Request["txtLocationCode"];
                location.LOCATIONTYPE = Request["LocationType"];
                location.WAREHOUSEID = Convert.ToInt32(Request["warehHuseId"]);
                location.GOODSRACK = Request["txtGOODSRACK"];
                location.TIER = Convert.ToDecimal(Request["txtTier"]);
                if (string.IsNullOrEmpty(Request["txtColumns"]))
                {
                    location.LOCOLUMNS = 0;
                }
                else
                {
                    location.LOCOLUMNS = Convert.ToDecimal(Request["txtColumns"]);
                }

                location.AREA = Request["txtArea"];

                string locationid = Request["hiddenLOCATIONID"];

                location.ROADWAY = "";
                if (string.IsNullOrEmpty(Request["txtVolume"]))
                {
                    location.VOLUME = Convert.ToDecimal(0);
                }
                else
                {
                    location.VOLUME = Convert.ToDecimal(Request["txtVolume"]);
                }
                location.COLUMNS = Convert.ToDecimal(Request["txtColumns"]);
                location.CREATER = model.USERCODE;
                location.ROADWAY = Request["txtRoadWay"];
                location.REMARK = Request["txtRemark"];
                location.CELLNO = Request["cellNo"];
                location.EDITOR = model.USERCODE;

                int n = 0;
                location.EDITOR = "";
                BLocationInfo nbl = new BLocationInfo();

                if (string.IsNullOrEmpty(locationid))
                {
                    Location checklocation = nbl.CheckLocation(location.LOCATIONCODE);

                    if (checklocation != null)
                    {
                        sjson = "{success:false,msg:'该货位编码已存在:" + location.LOCATIONCODE + "！'}";
                        return sjson;
                    }
                    else
                    {
                        n = nbl.AddLocation(location);
                        BAction action = new BAction();
                        ActionInfo ai = new ActionInfo();
                        ai.ACTIONTYPECODE = 2;
                        ai.OPERATION = "新增";
                        ai.OPCONTENT = "货位编码:" + location.LOCATIONCODE.ToString();
                        ai.OPERATIONOLD = "";
                        ai.OPERATIONNEW = "";
                        ai.USERCODE = model.USERCODE;
                        action.AddLmActionInfo(ai);
                    }

                }
                else
                {
                    location.LOCATIONID = int.Parse(locationid);
                    n = nbl.UpdateLocationByID(location);
                }


                if (n > 0)
                {
                    sjson = "{success:true}";
                }
                return sjson;


            }
            catch (Exception ex)
            {
                sjson = "{success:false,msg:'" + ex.Message + "'}";
            }
            return sjson;
        }

        #region 批量导入货位信息


        [HttpPost]
        public string ImportLocation()
        {
            string sjson = string.Empty;
            HttpPostedFileBase file = Request.Files["files"];
            DataTable table = new DataTable();
            string importStr = string.Empty;
            sjson = ImportFile(file, out table, out importStr);
            if (!string.IsNullOrEmpty(sjson))
                return sjson;

            TransactionOptions transactionOption = new TransactionOptions();

            //设置事务隔离级别
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

            // 设置事务超时时间为600秒
            transactionOption.Timeout = new TimeSpan(0, 0, 600);

            //引用事务机制，出错时，事物回滚
            using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required, transactionOption))
            {
                try
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        if (table.Rows[i][0] != null && table.Rows[i][0].ToString().Trim() != "")
                        {
                            string LocationCode = table.Rows[i][0].ToString();
                            string LocationType = table.Rows[i][1].ToString();
                            string WarehouseID = table.Rows[i][2].ToString();
                            string CellNo = table.Rows[i][3].ToString();
                            string GOODSRACK = table.Rows[i][4].ToString();
                            string Tier = table.Rows[i][5].ToString();
                            string Columns = table.Rows[i][6].ToString();
                            string Area = table.Rows[i][7].ToString();
                            string RoadWay = table.Rows[i][8].ToString();
                            string Volume = "";// table.Rows[i][10].ToString();
                            string Remark = "";//table.Rows[i][16].ToString();
                            Location location = new Location();

                            sjson = CheckLocation(string.Empty, LocationCode, LocationType, WarehouseID, CellNo, GOODSRACK, Tier, Columns, Area,
                                RoadWay, Volume, Remark, out location);

                            if (!string.IsNullOrEmpty(sjson))
                                return sjson;

                            BLocationInfo nbl = new BLocationInfo();
                            int n = nbl.AddLocation(location);
                            if (n > 0)
                            {
                                sjson = "{success:true}";
                            }
                        }
                    }

                    transaction.Complete();
                }
                catch (Exception ex)
                {
                    sjson = "{success:false,msg:'" + ex.Message + "'}";
                    return sjson;
                }
            }

            System.Threading.Thread.Sleep(2000);
            return sjson;
        }

        /// <summary>
        /// 检查导入信息是否匹配
        /// </summary>
        /// <param name="LOCATIONID"></param>
        /// <param name="LocationCode"></param>
        /// <param name="LocationType"></param>
        /// <param name="WarehouseID"></param>
        /// <param name="CellNo"></param>
        /// <param name="GOODSRACK"></param>
        /// <param name="Tier"></param>
        /// <param name="Columns"></param>
        /// <param name="Area"></param>
        /// <param name="RoadWay"></param>
        /// <param name="Volume"></param>
        /// <param name="Remark"></param>
        /// <param name="location"></param>
        /// <returns></returns>
        private string CheckLocation(string LOCATIONID, string LocationCode, string LocationType, string WarehouseID, string CellNo, string GOODSRACK, string Tier, string Columns,
            string Area, string RoadWay, string Volume, string Remark, out Location location)
        {
            string sjson = string.Empty;
            AppUserList model = (AppUserList)Session["UserInfo"];

            location = new Location();
            if (string.IsNullOrEmpty(LocationCode))
            {
                sjson = "{success:false,msg:'货位编码不能为空:" + LocationCode + "！'}";
                return sjson;
            }
            if (string.IsNullOrEmpty(LocationType))
            {
                sjson = "{success:false,msg:'货位类型不能为空:" + LocationCode + "！'}";
                return sjson;
            }
            if (string.IsNullOrEmpty(CellNo) && LocationType != "逻辑货位")
            {
                sjson = "{success:false,msg:'库位不能为空:" + LocationCode + "！'}";
                return sjson;
            }
            if (string.IsNullOrEmpty(WarehouseID))
            {
                sjson = "{success:false,msg:'仓库不能为空:" + LocationCode + "！'}";
                return sjson;
            }
            location.LOCATIONTYPE = LocationType;
            int TWarehouseID = 0;
            if (int.TryParse(WarehouseID, out TWarehouseID))
                location.WAREHOUSEID = TWarehouseID;
            location.GOODSRACK = GOODSRACK;
            decimal TTier = 0;
            if (decimal.TryParse(Tier, out TTier))
                location.TIER = TTier;
            decimal TColumns = 0;
            if (decimal.TryParse(Columns, out TColumns))
                location.COLUMNS = TColumns;
            location.AREA = Area;
            location.ROADWAY = RoadWay;
            decimal TVolume = 0;
            if (decimal.TryParse(Volume, out TVolume))
                location.VOLUME = TVolume;
            if (Remark != null && Remark != "")
            {
                location.REMARK = Remark;
            }
            else
            {
                location.REMARK = "批量导入";
            }

            location.LOCATIONCODE = LocationCode;
            location.CREATER = model.USERNAME;
            location.CREATEDATE = DateTime.Now;
            location.EDITOR = model.USERNAME;
            location.EDITDATE = DateTime.Now;
            location.CELLNO = CellNo;
            BLocationInfo nbl = new BLocationInfo();
            Location checklocation = nbl.CheckLocation(LocationCode);

            if (checklocation != null)
            {
                sjson = "{success:false,msg:'该货位编码已存在:" + LocationCode + "！'}";
                return sjson;
            }
            return sjson;
        }
        #endregion


        /// <summary>
        /// 导出货位信息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [HttpPost]
        public FileResult ExportExcelLocation()//导出execl
        {
            //创建Excel文件的对象
            HSSFWorkbook book = new HSSFWorkbook();
            //添加一个sheet
            ISheet sheet1 = book.CreateSheet("Sheet1");
            #region 获取list数据
            int total = 0;
            int n = 0;
            string warehHuseId = Request["sWarehHuseId"];
            string locationCode = Request["txtSlocationCode"];
            string locationType = Request["sLocationType"];
            string sArea = Request["txtSArea"];
            string roadWay = Request["txtSRoadWay"];
            string status = Request["status"];
            string where = " where 1=1";
            if (!string.IsNullOrEmpty(warehHuseId))
            {
                if (int.TryParse(warehHuseId, out n))
                {
                    if (Convert.ToInt32(warehHuseId) != 0)
                    {
                        where += " and l.warehouseid='" + warehHuseId + "'";
                    }
                }
                else
                {
                    where += " and 1=2";
                }
            }
            if (!string.IsNullOrEmpty(locationCode))
            {
                where += " and l.LOCATIONCODE like'%" + locationCode + "%'";
            }
            if (!string.IsNullOrEmpty(locationType))
            {
                where += " and l.LOCATIONTYPE like'%" + locationType + "%'";
            }
            if (!string.IsNullOrEmpty(sArea))
            {
                where += " and l.Area like'%" + sArea + "%'";
            }
            if (!string.IsNullOrEmpty(roadWay))
            {
                where += " and l.RoadWay like'%" + roadWay + "%'";
            }
            if (!string.IsNullOrEmpty(status))
            {
                where += " and l.STATUS ='" + status + "'";
            }


            BLocationInfo li = new BLocationInfo();
            List<Location> list = li.GetLocationInfoList(1, 10000, out total, where).ToList();
            #endregion
            //给sheet1添加第一行的头部标题
            IRow row1 = sheet1.CreateRow(0);
            List<string> lstTitle = new List<string> { "货位编码", "货位类型", "仓库", "库位", "货架", "层", "列", "区域", "巷道" };
            for (int i = 0; i < lstTitle.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(lstTitle[i]);
            }
            //将数据逐步写入sheet1各个行
            for (int i = 0; i < list.Count; i++)
            {
                IRow rowtemp = sheet1.CreateRow(i + 1);
                rowtemp.CreateCell(0).SetCellValue(list[i].LOCATIONCODE);
                rowtemp.CreateCell(1).SetCellValue(list[i].LOCATIONTYPE);
                rowtemp.CreateCell(2).SetCellValue(list[i].WAREHOUSENAME);
                rowtemp.CreateCell(3).SetCellValue(list[i].CELLNO);
                rowtemp.CreateCell(4).SetCellValue(list[i].GOODSRACK);
                rowtemp.CreateCell(5).SetCellValue(Convert.ToDouble(list[i].TIER));
                rowtemp.CreateCell(6).SetCellValue(Convert.ToDouble(list[i].COLUMNS));
                rowtemp.CreateCell(7).SetCellValue(list[i].AREA);
                rowtemp.CreateCell(8).SetCellValue(list[i].ROADWAY);
      
            }
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", NewTimeStamp("LocationGoods"));
        }

    }
}
